#include "main.h"

//数码管
uchar pos = 0;  //显示位置
uchar seg_str[16];//显示的字符
uchar seg_buf[8]; //字符段码
uchar show_mode = 1; //显示模式：1时间/日期，2温度，3ADC

//按键 
uchar key_val;
uchar key_old;

//ds1302
extern uchar DS1302_time[]; 
uchar time_mode = 1;

//ds18b20
extern float DS18B20_temp;
uchar temp_mode = 1;

//pcf8591 
extern uint PCF8591_val;
uchar adc_channel = PCF8591_AIN1;

//数据采集计数
uint pick_counter = 0;


//*******************main主程序*******************
void main() {
	sys_init();
	timer1_init();
	DS1302_init();
	
	led_proc();
	
	while(1) {		
		//数据采集
		if(++pick_counter > 300) {  
			pick_counter = 0;
			switch(show_mode) {
				case 1:
					DS1302_getTime();
				break;
				case 2:
					DS18B20_readTemp();
				break;
				case 3:
					PCF8591_ADC(adc_channel);
				break;
			}
		}
		
		key_proc();
		seg_proc();
	}
}

//*******************中断服务函数*******************
void timer1_isr() interrupt 3 {
	TH1 = (65535-2000)/256;  //2ms
	TL1 = (65535-2000)%256;
	
	//数码管显示
	seg_disp(pos, seg_buf);
	if(++pos >= 8) pos = 0;
}

//*******************LED*******************
void led_proc() {
	led_disp(0x01 << (show_mode-1));
}

//*******************数码管*******************
void seg_proc() {
	//待显示的字符数组
	switch(show_mode) {
		case 1: //时间
			if(time_mode == 1)
				sprintf(seg_str, "A1 %02d-%02d", (uint)DS1302_time[4], (uint)DS1302_time[5]);
			else if(time_mode == 2)
				sprintf(seg_str, "A2 %02d-%02d", (uint)DS1302_time[5], (uint)DS1302_time[6]);
			else
				sprintf(seg_str, "A3 %02d-%02d", (uint)DS1302_time[2], (uint)DS1302_time[3]);
		break;
		case 2: //温度
			if(temp_mode == 1)
				sprintf(seg_str, "C1   %03.1f", DS18B20_temp);
			else
				sprintf(seg_str, "C2   %03.1f", DS18B20_temp*9/5 + 32);
		break;
		case 3: //ADC
			if(adc_channel == PCF8591_AIN1)
				sprintf(seg_str, "P1   %03d", PCF8591_val);
			else if(adc_channel == PCF8591_AIN2)
				sprintf(seg_str, "P2   %03d", PCF8591_val);
			else
				sprintf(seg_str, "P3   %03d", PCF8591_val);
		break;
	}
	
	//将字符转换为段码
	seg_tran(seg_str, seg_buf);
}


//*******************按键*******************
void key_proc() {
	//读取按键按下的编号
	key_val = key_scan_btn();
	//key_val = key_scan(); //读取按键按下的编号
	key_val = key_val & (key_old^key_val);
	key_old = key_val;
	
	//数码管显示界面切换
	if(key_val == 4) {
		if(++show_mode > 3)
			show_mode = 1;
		led_proc();
	}
	//时间/日期显示切换
	else if(key_val == 5 && show_mode == 1) {
		if(++time_mode > 3)
			time_mode = 1;
	}
	//摄氏度/华氏度切换
	else if(key_val == 5 && show_mode == 2) {
		if(++temp_mode > 2)
			temp_mode = 1;
	}
	//ADC测量模式切换
	else if(key_val == 5 && show_mode == 3) {
		switch(adc_channel) {
			case PCF8591_AIN1:
				adc_channel = PCF8591_AIN2;
			break;
			case PCF8591_AIN2:
				adc_channel = PCF8591_AIN3;
			break;
			case PCF8591_AIN3:
				adc_channel = PCF8591_AIN1;
			break;
		}
	}
	
}

